<?php
/**
 * Created by PhpStorm.
 * User: lzhy@lzhy.me
 * Date: 2019/2/27 0027
 * Time: 17:09
 */
namespace Api\Event;

class WechatEvent
{
    /**
     * 获取当前用户当前公众号openid
     * @param $appId
     * @param $appSecret
     * @param bool $refresh
     * @return mixed
     */
    public static function getUserOpenId($appId,$appSecret,$refresh = false)
    {
        $openId = cookie('user_openid_'.$appId);
        if(empty($openId) || $refresh){
            $code = I('get.code');
            if(empty($code)){
                WechatEvent::jumpAuth($appId);
            }
            $openId = WechatEvent::getUserOpenIdOfCode($code,$appId,$appSecret);
            cookie('user_openid_'.$appId,$openId,600);
        }

        return $openId;
    }

    /**
     * 跳转授权
     * @param $appId
     * @param string $state
     */
    public static function jumpAuth($appId,$state = 'state')
    {
        $redirectUri = 'http://'.$_SERVER['SERVER_NAME'].'/api/';
        $urlParams = http_build_query([
            'appid' => $appId,
            'scope' => 'snsapi_base',
            'state' => $state,
            'response_type' => 'code',
            'redirect_uri'  => $redirectUri,
        ]);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?%s#wechat_redirect';
        header('Location:'.sprintf($url,$urlParams));
        exit();
    }

    /**
     * 用code换取用户openid
     * @param $code
     * @param $appId
     * @param $appSecret
     * @return mixed
     */
    public static function getUserOpenIdOfCode($code,$appId,$appSecret)
    {
        try{
            $urlParams = http_build_query([
                'appid'  => $appId,
                'secret' => $appSecret,
                'code'   => $code,
                'grant_type' => 'authorization_code'
            ]);
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?%s';
            $content = file_get_contents(sprintf($url,$urlParams));
            $content = json_decode($content,true);
            if(isset($content['errcode'])){
                //记录错误做出处理
                //self::jumpAuth($appId);
                exit($content['errmsg']);
            }
            return $content['openid'];
        }catch (\Exception $e){
            exit('获取openid错误：'.$e->getMessage());
        }
    }
}